package com.ktjiaoyu.service.impl;

//导入StringUtils用于获取文件名后缀名
import com.ktjiaoyu.service.UploadService;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service("toLocalUploadService")    //给bean命名
public class ToLocalUploadServiceImpl implements UploadService {
    private static final Logger logger = LoggerFactory.getLogger(ToLocalUploadServiceImpl.class);
//    上传文件的保存目录
    public static final String UPLOAD_PATH = "/statics/upload/";
    @Autowired
    private HttpServletRequest request; //注入HttpServletRequest

    @Override
    public String uploadFile(MultipartFile uploadFile, String... allowFileExtends) throws Exception {
        Set<String> include = new HashSet<>(Arrays.asList(allowFileExtends));
        //获取保存路径
        String rootPath = request.getServletContext().getRealPath(UPLOAD_PATH);
        //如果非空说明上传了文件数据
        if (!uploadFile.isEmpty()) {
            String fileName = uploadFile.getOriginalFilename();
            //获取文件名后缀
            String extension = StringUtils.getFilenameExtension(fileName);
            //如果不包含扩展名
            if (!include.contains(extension)) {
                throw new Exception("上传文件仅支持" + include + "扩展名，当前文件：" + fileName);
            }
            String uploadFileName = UUID.randomUUID() + "." + extension;
            File file = new File(rootPath, uploadFileName);
            //父级目录不存在是无法创建的
            if (!file.getParentFile().exists()) {
                //创建父级目录
                file.getParentFile().mkdirs();
            }
            try {
                uploadFile.transferTo(file);
                //返回文件路径
                return UPLOAD_PATH + uploadFileName;
            } catch (Exception e) {
                logger.error("执行ToLocalUploadServiceImpl"+ ".uploadFile(MultipartFile,String[])出现错误", e);
                throw e;
            }
        }
        return null;
    }
}
